package com.example.chat.controller;

import com.alibaba.excel.util.StringUtils;
import com.dragonsoftbravo.libs.OperationResult;
import com.dragonsoftbravo.libs.Opr;
import com.dragonsoftbravo.libs.PssLogFactory;
import com.example.chat.utils.ChatException;
import com.example.chat.utils.DOAException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<Opr<Void>> jsonErrorHandler(Exception e) {

        ResponseEntity<Opr<Void>> responseEntity;
        Opr<Void> opr = new Opr<>();
        if (e.getClass().equals(ChatException.class)) {
            ChatException lsgException = (ChatException) e;
            log.debug("lsg exception,code [{}], raiseBy [{}], message [{}]", lsgException.getCode(), lsgException.getRaiseBy(), lsgException.getMessage());
            opr.setResult(false).setCode(StringUtils.isEmpty(lsgException.getCode())? OperationResult.CommonCodes.REAULT_FAIL: lsgException.getCode()).setMsg(lsgException.getMessage());
            responseEntity = ResponseEntity.ok(opr);

        } else {
            opr.setResult(false).setCode(OperationResult.CommonCodes.REAULT_FAIL).setMsg("服务器异常");
            responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(opr);
        }
        log.error(this.getClass().getSimpleName(), e);
        return responseEntity;
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseBody
    public ResponseEntity<Opr<Void>> IllegalArgumentExceptionHandler(Exception e) {

        PssLogFactory.getErrorLog().error(this.getClass().getSimpleName(), e);
        Opr<Void> opr = new Opr<>();
        opr.setCode(OperationResult.CommonCodes.GENERAL_FAIL).setResult(false);
        opr.setMsg(e.getMessage());
        return new ResponseEntity(opr, HttpStatus.OK);
    }
}